package com.ex.sevice.impl;

import com.ex.dao.RoleDao;
import com.ex.dao.UserInfoDao;
import com.ex.model.SysRole;
import com.ex.model.UserInfo;
import com.ex.model.UserVo;
import com.ex.sevice.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoDao userInfoDao;

    @Resource
    private RoleDao roleDao;

    @Override
    public UserInfo findByUsername(String username) {
        System.out.println("UserInfoServiceImpl.findByUsername()");
        return userInfoDao.findByUsername(username);
    }

    @Override
    public void register(UserVo userInfo) {
        // 这里密码生成规则：
        // 用户名+密码 进行了两次md5散列
        UserInfo user = new UserInfo();
//        String password = new SimpleHash("MD5",userInfo.getPassword(),userInfo.getName(),2).toHex();
//        String salt = UUID.randomUUID().toString().replace("-","");
//        user.setName(userInfo.getName());
//        user.setPassword(password);
//        user.setSalt(salt);
//        user.setState((byte) 0);
//        userInfoDao.save(user);
//
//
//        UserInfo byUsername = userInfoDao.findByUsername(userInfo.getUsername());
//

        /*
        1.用户信息校验
        2.用户信息和数据信息校验
        3.密码生成
         */
        UserInfo byUsername = userInfoDao.findByUsername(userInfo.getUsername());
        if (!Objects.isNull(byUsername)) {
            log.info("{} -> {} -> {} ", this.getClass().getName(),
                    "register",
                    "用户名已存在");
            return;
        }
        String salt = UUID.randomUUID().toString().replace("-", "");
        String password = UUID.randomUUID().toString().replace("-", "");
        String newPassword = new SimpleHash("MD5", password, null, 2).toHex();
        BeanUtils.copyProperties(userInfo, user);
        user.setSalt(salt);
        user.setPassword(newPassword);

        String roles = userInfo.getRoles();
        SysRole sysRole = roleDao.findById(Integer.parseInt(roles)).get();
        if (null != sysRole) {
            user.getRoleList().add(sysRole);
            userInfoDao.save(user);
        }

        return;

    }
}